<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>事件监听器测试</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            max-width: 1000px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f7fa;
        }
        .test-card {
            background: white;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .test-title {
            color: #409eff;
            margin-bottom: 15px;
        }
        .test-button {
            background: #409eff;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 10px;
            margin-bottom: 10px;
        }
        .test-button:hover {
            background: #337ecc;
        }
        .test-button.danger {
            background: #f56c6c;
        }
        .test-button.danger:hover {
            background: #e74c3c;
        }
        .log-container {
            background: #1e1e1e;
            color: #d4d4d4;
            border-radius: 4px;
            padding: 15px;
            margin-top: 15px;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            max-height: 400px;
            overflow-y: auto;
            white-space: pre-wrap;
        }
        .status-success { color: #67c23a; }
        .status-error { color: #f56c6c; }
        .status-info { color: #909399; }
        .status-warning { color: #e6a23c; }
        .progress-bar {
            width: 100%;
            height: 20px;
            background-color: #f0f0f0;
            border-radius: 10px;
            overflow: hidden;
            margin: 10px 0;
        }
        .progress-fill {
            height: 100%;
            background-color: #409eff;
            transition: width 0.3s ease;
        }
        .task-info {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 4px;
            padding: 10px;
            margin: 10px 0;
        }
    </style>
</head>
<body>
    <h1>事件监听器测试</h1>
    
    <div class="test-card">
        <h2 class="test-title">1. Electron API 可用性测试</h2>
        <button class="test-button" onclick="testElectronAPI()">测试 Electron API</button>
        <div id="api-result" class="log-container" style="display: none;"></div>
    </div>

    <div class="test-card">
        <h2 class="test-title">2. 事件监听器设置测试</h2>
        <button class="test-button" onclick="testEventListeners()">设置事件监听器</button>
        <button class="test-button danger" onclick="removeEventListeners()">移除事件监听器</button>
        <div id="listener-result" class="log-container" style="display: none;"></div>
    </div>

    <div class="test-card">
        <h2 class="test-title">3. 模拟进度事件测试</h2>
        <button class="test-button" onclick="simulateProgressEvent()">模拟进度事件</button>
        <button class="test-button" onclick="simulateCompletedEvent()">模拟完成事件</button>
        <button class="test-button" onclick="simulateErrorEvent()">模拟错误事件</button>
        <div id="simulation-result" class="log-container" style="display: none;"></div>
    </div>

    <div class="test-card">
        <h2 class="test-title">4. 实时进度显示</h2>
        <div id="progress-display">
            <div class="task-info">
                <strong>任务状态:</strong> <span id="task-status">未开始</span>
            </div>
            <div class="progress-bar">
                <div class="progress-fill" id="progress-fill" style="width: 0%"></div>
            </div>
            <div class="task-info">
                <strong>下载进度:</strong> <span id="progress-text">0% (0 B / 0 B)</span>
            </div>
            <div class="task-info">
                <strong>片段进度:</strong> <span id="segment-text">0 / 0</span>
            </div>
            <div class="task-info">
                <strong>下载速度:</strong> <span id="speed-text">0 B/s</span>
            </div>
        </div>
    </div>

    <div class="test-card">
        <h2 class="test-title">5. 控制台日志</h2>
        <button class="test-button" onclick="clearLogs()">清除日志</button>
        <div id="console-log" class="log-container"></div>
    </div>

    <script>
        let eventListenersSet = false;
        let testTaskId = 'test-task-' + Date.now();
        let logs = [];

        // 日志函数
        function log(message, type = 'info') {
            const timestamp = new Date().toLocaleTimeString();
            const logEntry = `[${timestamp}] ${message}`;
            logs.push(logEntry);
            
            const logContainer = document.getElementById('console-log');
            logContainer.textContent = logs.join('\n');
            logContainer.scrollTop = logContainer.scrollHeight;
            
            console.log(logEntry);
        }

        // 清除日志
        function clearLogs() {
            logs = [];
            document.getElementById('console-log').textContent = '';
        }

        // 1. 测试 Electron API 可用性
        function testElectronAPI() {
            const resultDiv = document.getElementById('api-result');
            resultDiv.style.display = 'block';
            resultDiv.textContent = '';
            
            log('开始测试 Electron API 可用性...');
            
            if (typeof window !== 'undefined' && window.electronAPI) {
                log('✅ Electron API 可用');
                log('可用的方法: ' + Object.keys(window.electronAPI).join(', '));
                
                // 检查关键方法
                const requiredMethods = ['onDownloadProgress', 'onDownloadCompleted', 'onDownloadError'];
                const missingMethods = requiredMethods.filter(method => !window.electronAPI[method]);
                
                if (missingMethods.length === 0) {
                    log('✅ 所有必需的事件监听器方法都可用');
                } else {
                    log('❌ 缺少必需的方法: ' + missingMethods.join(', '));
                }
                
                resultDiv.textContent = logs.slice(-10).join('\n');
            } else {
                log('❌ Electron API 不可用');
                log('window.electronAPI: ' + (window.electronAPI ? '存在' : '不存在'));
                resultDiv.textContent = logs.slice(-10).join('\n');
            }
        }

        // 2. 设置事件监听器
        function testEventListeners() {
            const resultDiv = document.getElementById('listener-result');
            resultDiv.style.display = 'block';
            resultDiv.textContent = '';
            
            log('开始设置事件监听器...');
            
            if (!window.electronAPI) {
                log('❌ Electron API 不可用，无法设置事件监听器');
                resultDiv.textContent = logs.slice(-10).join('\n');
                return;
            }
            
            try {
                // 设置进度事件监听器
                window.electronAPI.onDownloadProgress((event, data) => {
                    log('📊 收到进度事件: ' + JSON.stringify(data));
                    updateProgressDisplay(data);
                });
                
                // 设置完成事件监听器
                window.electronAPI.onDownloadCompleted((event, data) => {
                    log('✅ 收到完成事件: ' + JSON.stringify(data));
                    updateProgressDisplay(data);
                });
                
                // 设置错误事件监听器
                window.electronAPI.onDownloadError((event, data) => {
                    log('❌ 收到错误事件: ' + JSON.stringify(data));
                    updateProgressDisplay(data);
                });
                
                eventListenersSet = true;
                log('✅ 事件监听器设置成功');
                resultDiv.textContent = logs.slice(-10).join('\n');
                
            } catch (error) {
                log('❌ 设置事件监听器失败: ' + error.message);
                resultDiv.textContent = logs.slice(-10).join('\n');
            }
        }

        // 移除事件监听器
        function removeEventListeners() {
            log('移除事件监听器...');
            
            if (window.electronAPI && window.electronAPI.removeAllListeners) {
                window.electronAPI.removeAllListeners('download-progress');
                window.electronAPI.removeAllListeners('download-completed');
                window.electronAPI.removeAllListeners('download-error');
                log('✅ 事件监听器已移除');
            } else {
                log('❌ 无法移除事件监听器');
            }
            
            eventListenersSet = false;
        }

        // 3. 模拟事件
        function simulateProgressEvent() {
            log('模拟进度事件...');
            
            const mockData = {
                taskId: testTaskId,
                status: 'downloading',
                downloadedSize: Math.floor(Math.random() * 100 * 1024 * 1024), // 0-100MB
                totalSize: 100 * 1024 * 1024, // 100MB
                downloadedSegments: Math.floor(Math.random() * 50),
                totalSegments: 50,
                downloadSpeed: Math.floor(Math.random() * 1024 * 1024) // 0-1MB/s
            };
            
            log('发送模拟进度数据: ' + JSON.stringify(mockData));
            updateProgressDisplay(mockData);
        }

        function simulateCompletedEvent() {
            log('模拟完成事件...');
            
            const mockData = {
                taskId: testTaskId,
                status: 'completed',
                downloadedSize: 100 * 1024 * 1024, // 100MB
                totalSize: 100 * 1024 * 1024, // 100MB
                outputFile: '/path/to/completed/video.mp4'
            };
            
            log('发送模拟完成数据: ' + JSON.stringify(mockData));
            updateProgressDisplay(mockData);
        }

        function simulateErrorEvent() {
            log('模拟错误事件...');
            
            const mockData = {
                taskId: testTaskId,
                status: 'error',
                error: '模拟的网络错误'
            };
            
            log('发送模拟错误数据: ' + JSON.stringify(mockData));
            updateProgressDisplay(mockData);
        }

        // 更新进度显示
        function updateProgressDisplay(data) {
            const statusElement = document.getElementById('task-status');
            const progressFill = document.getElementById('progress-fill');
            const progressText = document.getElementById('progress-text');
            const segmentText = document.getElementById('segment-text');
            const speedText = document.getElementById('speed-text');
            
            // 更新状态
            statusElement.textContent = data.status || '未知';
            
            // 更新进度条
            if (data.downloadedSize && data.totalSize) {
                const progress = Math.floor((data.downloadedSize / data.totalSize) * 100);
                progressFill.style.width = progress + '%';
                progressText.textContent = `${progress}% (${formatFileSize(data.downloadedSize)} / ${formatFileSize(data.totalSize)})`;
            }
            
            // 更新片段进度
            if (data.downloadedSegments !== undefined && data.totalSegments !== undefined) {
                segmentText.textContent = `${data.downloadedSegments} / ${data.totalSegments}`;
            }
            
            // 更新下载速度
            if (data.downloadSpeed !== undefined) {
                speedText.textContent = formatFileSize(data.downloadSpeed) + '/s';
            }
        }

        // 文件大小格式化
        function formatFileSize(bytes) {
            if (!bytes || bytes === 0) return '0 B';
            const k = 1024;
            const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        // 页面加载完成后的初始化
        document.addEventListener('DOMContentLoaded', function() {
            log('事件监听器测试页面已加载');
            log('当前时间: ' + new Date().toLocaleString());
            
            // 自动测试 Electron API
            setTimeout(() => {
                testElectronAPI();
            }, 1000);
        });
    </script>
</body>
</html>
